var express = require('express');
var router = express.Router();
const shortId = require('shortid')
const UrlModel = require('../models/urlModel')



/* GET users listing. DGVEvfviOVAGRtx6AQygynVzsj6tUpf5 */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

router.post('/url', async function (req, res, next) {
    const { url } = req.body;
    shortId.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$*')
    const shortUrl = shortId.generate()
    const data = await UrlModel.findOne({ longUrl: url })
    const resp = await UrlModel.create({ shortUrl, longUrl: url })
    res.send({url: req.headers.host + req.baseUrl + '/' + resp.shortUrl})
})

router.get('/:code', async (req, res, next) => {
    const code = req.params.code
    const urls = await UrlModel.findOne({ shortUrl: code })
    if (urls) {
        res.redirect(urls.longUrl)
    }
})

module.exports = router;
